package com.zhl.controller;

import com.zhl.entity.Article;
import com.zhl.entity.Function;
import com.zhl.entity.ZhlResult;
import com.zhl.service_.FunctionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by Administrator on 2018/11/6.
 */
@Controller
public class FunctionController {

    Logger logger = LoggerFactory.getLogger("FunctionController");

    @Autowired
    private FunctionService functionService;

    @RequestMapping("/api/function")
    @ResponseBody
    public ZhlResult functionList() {

        List<Function> functions = functionService.functionList();
        return ZhlResult.ok(functions);
    }

    @RequestMapping("/api/addfunction")
    @ResponseBody
    public ZhlResult addFunction(HttpServletRequest request, Function function) {

        functionService.addFunction(function);
        return ZhlResult.ok();
    }

    /**
     * 根据id查询权限
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/api/queryfunction/{id}")
    public String addFunction(@PathVariable("id") String id, Model model) {

        Function function = functionService.queryFunctionById(id);
        model.addAttribute("function",function);
        return "/admin/updatefunction.html";
    }

    /**
     * 删除日记
     *
     */
    @RequestMapping("/api/deleteFunction/{id}")
    @ResponseBody
    public ZhlResult deleteFunction(@PathVariable("id") String id, Model model) {
        logger.info("查询权限,id:"+id);

        Function oldFunction = functionService.queryFunctionById(id);
        if(oldFunction== null) {
            return ZhlResult.build(400,"该id没有对用的权限");
        }

        functionService.deleteFunction(id);
        return ZhlResult.ok();

    }

    @RequestMapping("/api/updatefunction")
    @ResponseBody
    public ZhlResult updateFunction(HttpServletRequest request, Function function) {

        Function oldFunction = functionService.queryFunctionById(function.getFid());
        oldFunction.setName(function.getName());
        oldFunction.setUrl(function.getUrl());
        oldFunction.setDescription(function.getDescription());
        oldFunction.setZindex(function.getZindex());
        functionService.updateFunction(oldFunction);

        return ZhlResult.ok();
    }


}
